package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import org.example.Entity.Dish;
import org.example.Entity.DishFlavor;
import org.example.Entity.SetmealDish;
import org.example.Mapper.DishMapper;
import org.example.common.CustomException;
import org.example.dto.DishDto;
import org.example.service.DishFlavorService;
import org.example.service.DishService;
import org.example.service.SetmealDishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends MPJBaseServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增菜品，同时保存对应的口味数据
     * @param dishDto
     */
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品基本信息
        super.save(dishDto);

        //保存菜品口味
        List<DishFlavor> flavorList = dishDto.getFlavors().stream().map(item -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavorList);
    }

    /**
     * 更新菜品，同时更新对应的口味数据
     * @param dishDto
     */
    public void updateWithFlavor(DishDto dish) {
        //更新dish实体
        super.updateById(dish);
        //删除原来的flavor
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        dishFlavorService.remove(queryWrapper);
        //插入flavors(传入的flavors的id可能存在丢失，只能使用先删后插的方法)
        List<DishFlavor> flavors = dish.getFlavors();
        flavors = flavors.stream().map(item -> {
            item.setDishId(dish.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public void removeDishes(List<Long> ids) {
        //1.判断是否停售,若未停售抛出异常
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getStatus,1)
                .in(Dish::getId,ids);
        int count = this.count(queryWrapper);
        if (count > 0) throw new CustomException("请先停售所选的菜品！");
        //2.判断是否关联了套餐,若关联了套餐抛出异常
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getDishId,ids);
        int count1 = setmealDishService.count(queryWrapper1);
        if (count1 > 0) throw new CustomException("所选的菜品正在被套餐关联，请先删除关联的套餐！");
        //3.删除菜品表数据
        this.removeByIds(ids);
    }
}
